/*
 * Copyright (c) 2009 Nathaniel Houghton <nathan@brainwerk.org>
 *                    Robert Kirchgessner <rkirchge@gmail.com>
 *
 * Permission to use, copy, modify, and distribute this software for
 * any purpose with or without fee is hereby granted, provided that
 * the above copyright notice and this permission notice appear in all
 * copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
 * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
 * AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
 * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA
 * OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
 * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 * PERFORMANCE OF THIS SOFTWARE.
 *
 */

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

#include "config.h"
#include "usart.h"
#include "ui.h"
#include "event.h"
#include "elm.h" 
#include "mode.h"

void
log_mode(struct mode *mode)
{
	int r;
	struct cmd cmd;
	char buf[32];
	
	if (mode->state != STATE_FF_END) {
		if (ui_mode_change(mode))
			return;

		parse_line(&cmd);
		if (ser_mode_change(mode, &cmd))
			return;
	}

	switch (mode->state) {
	case STATE_0_INIT:
		/*
		 * Initialize the ELM with ISO9141 as starting
		 * protocol.
		 */
		r = elm_init( &myelm, PROT_ISO9141 );
		if (!r) {
			elm_reset();
			return;
		}

		snprintf(buf, sizeof(buf), "Mode: %s",
			mode_str[mode->mode]);
		lcd_update(&lcd, 0, buf);
		lcd_update(&lcd, 1, "");

		events_start(cfg.nvm_start_addr);

		change_state(mode, 1);

		break;

	case 1:
		events(mode);
		break;

	case STATE_FF_END:
		r = events_end(&cfg.nvm_start_addr);

		/*
		 * We actually logged something, update eeprom start
		 * address.
		 */
		if (r) {
			usart_puts(0, "updating config\r\n");
			write_config(&cfg);
		}

		/* If we still arent initialized... */
		if (myelm.initd == 0) {
			usart_puts(0, "Mode change failed. Could "
			    "not initialize ELM.\r\n");
			snprintf(buf, sizeof(buf), "Mode: %s",
			    mode_str[mode->mode]);
			lcd_update(&lcd, 0, buf);
		}
		break;
	}
}
